package com.taomus.mytools.lang.jruby;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;

import org.jruby.Ruby;
import org.jruby.RubyRuntimeAdapter;
import org.jruby.javasupport.JavaEmbedUtils;

import com.taomus.mytools.lang.exception.GetClassException;
import com.taomus.mytools.lang.exception.InstanceException;
import com.taomus.mytools.lang.inter.DSLangUtils;
import com.taomus.mytools.lang.inter.IMethod;

public class JRubyUtils extends DSLangUtils{

	@Override
	public IMethod newInstance(String name,boolean isCache)  throws InstanceException,GetClassException{
		String filename = null;
		if (name.endsWith(".rb")) {
			filename = name;
			name = name.substring(name.lastIndexOf("/") + 1);
			name = name.replace(".rb", "");
			System.out.println(name);
		}
		if (filename != null) {
			InputStream input;
			try {
				input = new FileInputStream(filename);
				ArrayList<String> loadPaths = new ArrayList<String>();
				loadPaths.add("/root/.jruby/lib/ruby/1.8");
				loadPaths.add("/root/.jruby/lib/ruby/site_ruby/1.8");
				Ruby runtime = JavaEmbedUtils.initialize(loadPaths);
				RubyRuntimeAdapter evaler = JavaEmbedUtils.newRuntimeAdapter();
				return new JRubyMethod(name, runtime, evaler, input, filename);
			} catch (FileNotFoundException e) {
				throw new InstanceException(e);
			}
		}
		return null;
	}

	@Override
	public Class<?> getClass(String name) {
		return null;
	}

}
